package com.lee.forum.interceptor;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-09-30
 * Time: 12:14
 */

import com.lee.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    // 从配置⽂件中获取默认登录⻚的URL
    @Value("${forum.login.url}")
    private String defaultURL;

    /**
     * 预处理(请求的前置处理)回调⽅法<br/>
     * 返回值: <br/>true 流程继续;<br/>
     * false流程中断, 不会再调⽤其他的拦截器
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 获取⽤⼾session, 并判断用户是否登录
        HttpSession session = request.getSession();
        if (session != null && session.getAttribute(AppConfig.USER_SESSION_KEY) != null) {
            // 用户已登录
            return true;
        }
        // 用户未登录，跳转到登录页面
//        if (!defaultURL.startsWith("/")) {
//            defaultURL = "/"+defaultURL;
//        }
        System.out.println("进行登录拦截，跳转路径："+defaultURL);
        response.sendRedirect("/sign-in.html");
        return false;
    }
}
